package netWork;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

public class UdpDictSever {

    //端口号
    private static final int port = 4444;
    //用hashMap
    HashMap<String,String> hashMap = null;
   private DatagramSocket socket = null;
    //单词翻译服务器
    public static void main(String[] args) throws IOException {
        //创建socket对象
        UdpDictSever udpDictSever = new UdpDictSever();
        udpDictSever.start();
    }
    public UdpDictSever() throws SocketException {
    //构造方法
        socket = new DatagramSocket(port);
       hashMap = new HashMap<>();
        hashMap.put("cat","小猫");
        hashMap.put("小狗","dog");
        hashMap.put("小羊","sheep");
        hashMap.put("小猪","pig");
        hashMap.put("小兔","rabbit");
    }


    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true){
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(requestPacket);
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            String response = process(request);
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),
                    response.getBytes().length, requestPacket.getSocketAddress());
            socket.send(responsePacket);
            System.out.printf("[%s:%d] req: %s ,resp %s\n",requestPacket.getAddress().toString(),requestPacket.getPort(),request,response);

        }

    }

    private String process(String request) {

        return hashMap.getOrDefault(request,"没找到") ;
    }

}
